package org.zyj.io.example.case3;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class ChatClient {

    private final String host = "127.0.0.1";
    private final int port = 9988;

    public void run() throws InterruptedException {
        var eventLoop = new NioEventLoopGroup();
        try {
            var bootstrap = new Bootstrap();
            bootstrap.group(eventLoop).channel(NioSocketChannel.class)//
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            var pipeline = ch.pipeline();
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            pipeline.addLast("clientHandler", new ChatClientHandler());
                        }
                    });
            var channelFuture = bootstrap.connect(host, port).sync();
            System.out.println("连接成功: " + channelFuture.channel().remoteAddress());
            var scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                var s = scanner.nextLine();
                //向服务端发送消息
                channelFuture.channel().writeAndFlush(s);
            }

        } finally {
            eventLoop.shutdownGracefully();
        }
    }

}
